package com.mvp.shq.washer.ui.recharge;


import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.TextView;

import com.alipay.sdk.app.PayTask;
import com.mvp.shq.washer.R;
import com.mvp.shq.washer.adapter.RechargeAdapter;
import com.mvp.shq.washer.base.BaseFragment;
import com.mvp.shq.washer.entity.RechargeBean;
import com.mvp.shq.washer.entity.WxPayBean;
import com.mvp.shq.washer.entity.result.AlipayResult;
import com.mvp.shq.washer.entity.result.AuthResult;
import com.mvp.shq.washer.entity.PayResult;
import com.mvp.shq.washer.entity.RechargeMoney;
import com.mvp.shq.washer.entity.RechargeResponse;
import com.mvp.shq.washer.entity.User;
import com.mvp.shq.washer.rxbus.BusData;
import com.mvp.shq.washer.rxbus.RxBus;
import com.mvp.shq.washer.rxbus.Subscribe;
import com.mvp.shq.washer.utils.EventCode;
import com.mvp.shq.washer.utils.JumpUtil;
import com.mvp.shq.washer.utils.RecyclerViewDivider;
import com.mvp.shq.washer.utils.SpUtil;
import com.mvp.shq.washer.utils.T;
import com.orhanobut.logger.Logger;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.zhy.autolayout.AutoRelativeLayout;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * A simple {@link Fragment} subclass.
 */
public class RechargeFragment extends BaseFragment<RechargePresenter, RechargeModel> implements RechargeConstract.View {

    @BindView(R.id.back)
    ImageView back;
    @BindView(R.id.title)
    TextView title;
    @BindView(R.id.tv_balance)
    TextView tvBalance;
    @BindView(R.id.recyclerview)
    RecyclerView recyclerview;
    @BindView(R.id.rg_wx)
    RadioButton rgWx;
    @BindView(R.id.arl_wx_pay)
    AutoRelativeLayout arlWxPay;
    @BindView(R.id.rg_alipay)
    RadioButton rgAlipay;
    @BindView(R.id.arl_alipay_pay)
    AutoRelativeLayout arlAlipayPay;
    @BindView(R.id.btn_recharge)
    Button btnRecharge;
    @BindView(R.id.tv_given)
    TextView tvGiven;
    @BindView(R.id.tv_recharge_rule)
    TextView tvRule;
    private User user;
    private RechargeAdapter adapter;
    private List<RechargeBean> moneys;
    private int selectPosition = 0;
    private String APP_ID = "wx18074b4c6adce3f8";
    private IWXAPI api;
    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG: {
                    @SuppressWarnings("unchecked")
                    PayResult payResult = new PayResult((Map<String, String>) msg.obj);
                    /**
                     对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                     */
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                    String resultStatus = payResult.getResultStatus();
                    // 判断resultStatus 为9000则代表支付成功
                    if (TextUtils.equals(resultStatus, "9000")) {
                        // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
                        //Toast.makeText(PayDemoActivity.this, "支付成功", Toast.LENGTH_SHORT).show();
                        T.show("支付成功");
                        RxBus.get().send(EventCode.GET_USER_INFO);
                    } else {
                        // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
                        //Toast.makeText(PayDemoActivity.this, "支付失败", Toast.LENGTH_SHORT).show();
                        T.show("支付失败");
                    }
                    break;
                }
                case SDK_AUTH_FLAG: {
                    @SuppressWarnings("unchecked")
                    AuthResult authResult = new AuthResult((Map<String, String>) msg.obj, true);
                    String resultStatus = authResult.getResultStatus();

                    // 判断resultStatus 为“9000”且result_code
                    // 为“200”则代表授权成功，具体状态码代表含义可参考授权接口文档
                    if (TextUtils.equals(resultStatus, "9000") && TextUtils.equals(authResult.getResultCode(), "200")) {
                        // 获取alipay_open_id，调支付时作为参数extern_token 的value
                        // 传入，则支付账户为该授权账户
//                        Toast.makeText(PayDemoActivity.this,
//                                "授权成功\n" + String.format("authCode:%s", authResult.getAuthCode()), Toast.LENGTH_SHORT)
//                                .show();
                        T.show("授权成功");
                    } else {
                        // 其他状态值则为授权失败
//                        Toast.makeText(PayDemoActivity.this,
//                                "授权失败" + String.format("authCode:%s", authResult.getAuthCode()), Toast.LENGTH_SHORT).show();
                        T.show("授权失败");

                    }
                    break;
                }
                default:
                    break;
            }
        };
    };

    @Override
    public int getLayoutId() {
        return R.layout.fragment_recharge;
    }

    @Override
    public void initView() {
        title.setText("充值");
        back.setVisibility(View.GONE);
        recyclerview.setLayoutManager(new GridLayoutManager(context,3,LinearLayoutManager.VERTICAL,false));
        RecyclerViewDivider divider1 = new RecyclerViewDivider(context,LinearLayoutManager.VERTICAL,28,getResources().getColor(R.color.white));
        recyclerview.addItemDecoration(divider1);
        rgWx.setChecked(true);
        initUser();
    }
    @Subscribe(code = EventCode.UPDATE_USER)
    public void initUser(){
        user = SpUtil.getUser();
        if (user != null){
            tvBalance.setText(user.getRechargeBalance().add(user.getGivenMoney())+"");
        }else {
            tvBalance.setText("0");
        }
    }
    @Subscribe(code = EventCode.LOGIN_OUT)
    public void loginOut(){
        initUser();
    }
    @OnClick({R.id.all_rule,R.id.arl_wx_pay, R.id.arl_alipay_pay, R.id.btn_recharge,R.id.rg_alipay,R.id.rg_wx})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.arl_wx_pay:
                rgWx.setChecked(true);
                rgAlipay.setChecked(false);
                break;
            case R.id.arl_alipay_pay:
                rgWx.setChecked(false);
                rgAlipay.setChecked(true);
                break;
            case R.id.rg_alipay:
                rgWx.setChecked(false);
                rgAlipay.setChecked(true);
                break;
            case R.id.rg_wx:
                rgWx.setChecked(true);
                rgAlipay.setChecked(false);
                break;
            case R.id.btn_recharge:
                if (SpUtil.getUser() == null){
                    JumpUtil.toLogin(context);
                    return;
                }
                RechargeResponse response = new RechargeResponse();
                response.setUserId(SpUtil.getUser().getId());
                response.setRechargeMoney(new BigDecimal(moneys.get(selectPosition).getLabel()));
                if (rgAlipay.isChecked()){
                    response.setPayType(1);
                    presenter.alipay(response);
                }
                if (rgWx.isChecked()){
                    response.setPayType(0);
                    presenter.wxPay(response);
                }
                break;
            case R.id.all_rule:
                JumpUtil.toRule(context,"recharge");
                break;
        }
    }
    @Subscribe(code = EventCode.ON_RECHARGEMONEY_CLICK)
    public void onItemClick(BusData data){
        int position = data.getPosition();
        if (position == selectPosition){
            return;
        }
        moneys.get(selectPosition).setSelect(false);
        moneys.get(position).setSelect(true);
        selectPosition = position;
        adapter.notifyDataSetChanged();
        setGivenTV();
    }

    @Override
    public void getRecharMoneySuccess(List<RechargeMoney> list) {

    }
    public void setGivenTV(){
        if (moneys.get(selectPosition) == null){
            tvGiven.setText("");
            return;
        }
        String str = "赠送" + moneys.get(selectPosition).getValue() + "元";
        tvGiven.setText(str);
    }
    private static final int SDK_PAY_FLAG = 1;
    private static final int SDK_AUTH_FLAG = 2;
    private void alipay(String orderInfo){
        Runnable payRunnable = new Runnable() {

            @Override
            public void run() {
                PayTask alipay = new PayTask(getActivity());
                Map<String, String> result = alipay.payV2(orderInfo, true);
                Message msg = new Message();
                msg.what = SDK_PAY_FLAG;
                msg.obj = result;
                mHandler.sendMessage(msg);
            }
        };
        // 必须异步调用
        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }
    @Override
    public void getRecharMoneyFail(String msg) {
        T.show("获取充值金额失败");
    }

    @Override
    public void alipayS(AlipayResult result) {
        if (result==null || !result.isSuccess()){
            T.show("未知错误");
            return;
        }
        alipay(result.getBody());
    }

    @Override
    public void wxPayS(WxPayBean payBean) {
        api = WXAPIFactory.createWXAPI(context,null);
        api.registerApp(payBean.getAppid());
        PayReq request = new PayReq();
        request.appId = payBean.getAppid();
        request.partnerId = payBean.getPartnerid();
        request.prepayId = payBean.getPrepayid();
        request.packageValue = payBean.getPackageX();
        request.nonceStr = payBean.getNoncestr();
        request.timeStamp = payBean.getTimestamp();
        request.sign = payBean.getSign();
        api.sendReq(request);
    }

    @Override
    public void getRechargeMoneyS(List<RechargeBean> list) {
        if (list == null){
            return;
        }
        moneys = new ArrayList<>();
        for (int i=0;i<list.size();i++){
            list.get(i).setSelect(false);
            moneys.add(list.get(i));
        }
        selectPosition = 0;
        if (moneys.size() >= 1){
            moneys.get(selectPosition).setSelect(true);
        }
        setGivenTV();
        adapter = new RechargeAdapter(context,moneys);
        recyclerview.setAdapter(adapter);
    }
}
